<template>
    <div class="container">
        <van-form @submit="onSubmit">
            <div class="qiye-info">
                <div class="title">项目信息</div>
                <van-cell-group inset>
                  <van-field
                    v-model="prolevelValue"
                    is-link
                    label="项目级别："
                    placeholder="请选择项目级别"
                    required
                    @click="showPicker3 = true"
                    :rules="[{ required: true, message: '请选择项目级别' }]"
                  />
                  <van-popup v-model:show="showPicker3" round position="bottom">
                    <van-picker
                      :columns="prolevelList"
                      @cancel="showPicker3 = false"
                      @confirm="onConfirm3"
                    />
                  </van-popup>

                  <van-field
                    v-model="form.projectName"
                    name="projectName"
                    label="项目名称："
                    placeholder="请输入项目名称"
                    required
                    :rules="[{ required: true, message: '请输入项目名称' }]"
                    />
                    <van-field
                    v-model="form.projectCode"
                    name="projectCode"
                    label="项目编号："
                    placeholder="请输入项目编号"
                    />
                    
                  <van-field
                  v-model="form.approvalTime"
                  name="approvalTime"
                  label="立项时间："
                  placeholder="请选择立项时间"
                  readonly
                  required
                  :rules="[{ required: true, message: '请选择立项时间' }]"
                  @click="showApprovalTime = true"
                  />
                  <van-popup v-model:show="showApprovalTime" round position="bottom">
                      <van-date-picker
                      title="选择年月"
                      v-model="currentDate"
                      :columns-type="columnsType"
                      :formatter="formatter"
                      @confirm="onConfirmTime"
                      @cancel = "showApprovalTime = false"
                    />
                  </van-popup>

                  <van-field
                    v-model="inputValue"
                    name="projectAmount"
                    label="项目规定时长："
                    placeholder="请输入项目规定时长"
                    type="number"
                    required
                    :rules="[{ required: true, message: '请输入项目规定时长' }]"
                    >
                    <template #button>
                        <div size="small" type="primary">月</div>
                      </template>
                  </van-field>

                  <van-field
                    v-model="isjxValue"
                    is-link
                    label="是否结项："
                    placeholder="请选择是否结项"
                    @click="showPicker2 = true"
                    required
                    :rules="[{ required: true, message: '请选择是否结项' }]"
                  />
                  <van-popup v-model:show="showPicker2" round position="bottom">
                    <van-picker
                      :columns="isjxList"
                      @cancel="showPicker2 = false"
                      @confirm="onConfirm2"
                    />
                  </van-popup>
                    <van-field
                    v-model="companyValue"
                    is-link
                    readonly
                    label="所属单位："
                    placeholder="请选择所属单位"
                    required
                    @click="showPickerCompany = true"
                    :rules="[{ required: true, message: '请选择所属单位' }]"
                  />
                  <van-popup v-model:show="showPickerCompany" round position="bottom">
                    <van-picker
                      :columns="companyList"
                      @cancel="showPickerCompany = false"
                      @confirm="onConfirmCompany"
                    />
                  </van-popup>

                    <van-field
                    v-model="talentValue"
                    is-link
                    readonly
                    label="负责人："
                    placeholder="请选择负责人"
                    required
                    @click="showPicker1 = true"
                    :rules="[{ requiRd: true, message: '请选择负责人' }]"
                  />
                  <van-popup v-model:show="showPicker1" round position="bottom">
                    <van-picker
                      :columns="talentList"
                      @cancel="showPicker1 = false"
                      @confirm="onConfirm1"
                    />
                  </van-popup>
                    <van-field
                    v-model="form.phone"
                    name="phone"
                    label="联系方式："
                    placeholder="请输入联系方式"
                    required
                    :rules="[{ required: true, message: '请输入联系方式' }]"
                    />

                    <van-field
                    v-model="form.projectAmount"
                    name="projectAmount"
                    label="总额："
                    placeholder="请输入总额"
                    type="number"
                    required
                    :rules="[{ required: true, message: '请输入总额' }]"
                    >
                    <template #button>
                        <div size="small" type="primary">万元</div>
                      </template>
                    </van-field>

                    <van-field
                    v-model="directionValue"
                    is-link
                    label="投资方向："
                    placeholder="请选择投资方向"
                    @click="showPickerDirection = true"
                    required
                    :rules="[{ required: true, message: '请选择投资方向' }]"
                  />
                  <van-popup v-model:show="showPickerDirection" round position="bottom">
                    <van-picker
                      :columns="directionList"
                      @cancel="showPickerDirection = false"
                      @confirm="onConfirmDirection"
                    />
                  </van-popup>

                  <van-field
                    v-model="departmentValue"
                    is-link
                    label="立项部门："
                    placeholder="请选择立项部门"
                    @click="showPickerDepartment = true"
                    required
                    :rules="[{ required: true, message: '请选择立项部门' }]"
                  />
                  <van-popup v-model:show="showPickerDepartment" round position="bottom">
                    <van-picker
                      :columns="departmentList"
                      @cancel="showPickerDepartment = false"
                      @confirm="onConfirmDepartment"
                    />
                  </van-popup>

                  <van-field
                    v-model="zzxmValue"
                    is-link
                    label="资助项目名称："
                    required
                    placeholder="请选择资助项目名称"
                    @click="showPickerzzxm = true"
                    :rules="[{ required: true, message: '请选择资助项目名称' }]"
                  />
                  <van-popup v-model:show="showPickerzzxm" round position="bottom">
                    <van-picker
                      :columns="zzxmList"
                      @cancel="showPickerzzxm = false"
                      @confirm="onConfirmZzxm"
                    />
                  </van-popup>

                  <van-field
                    v-model="form.subsidizeAmount"
                    name="projectAmount"
                    label="项目资助金额："
                    placeholder="请输入项目资助金额"
                    type="number"
                    required
                    :rules="[{ required: true, message: '请输入项目资助金额' }]"
                    >
                    <template #button>
                        <div size="small" type="primary">万元</div>
                      </template>
                    </van-field>

                    <!-- <van-field
                    v-model="zzjdValue"
                    is-link
                    label="项目资助阶段："
                    placeholder="请选择项目资助阶段"
                    @click="showPickerzzjd = true"
                    :rules="[{ required: true, message: '请选择项目资助阶段' }]"
                  />
                  <van-popup v-model:show="showPickerzzjd" round position="bottom">
                    <van-picker
                      :columns="zzjdList"
                      @cancel="showPickerzzjd = false"
                      @confirm="onConfirmZzjd"
                    />
                  </van-popup> -->
                  
                  <!-- <van-field
                    v-model="form.subsidizeTime"
                    name="subsidizeTime"
                    label="项目资助时间："
                    placeholder="请选择项目资助时间"
                    readonly
                    :rules="[{ required: true, message: '请选择项目资助时间' }]"
                    @click="isDatePickerVisible = true"
                    />
                  <van-popup v-model:show="isDatePickerVisible" round position="bottom">
                      <van-date-picker
                      title="选择年月"
                      :columns-type="columnsType"
                      :formatter="formatter"
                      @confirm="onConfirmTime2"
                    />
                  </van-popup> -->

                  <van-field
                    v-model="form.intro"
                    name="intro"
                    label="项目简介："
                    placeholder="请输入项目简介"
                    :rules="[{ required: true, message: '请输入项目简介' }]"
                    />
                </van-cell-group>
            </div>
          <div class="addbtn">
            <van-button color='#1052CC' block type="primary" native-type="submit">
              确定
            </van-button>
          </div>
        </van-form>

    </div>
</template>
 
<script setup>
import { ref,reactive,onMounted,watch } from 'vue';
import { useRouter,useRoute } from 'vue-router';
import { showToast } from 'vant';
import { getProjectDetail,getTalentList,editProject,creatProject,getDictSelect, getCompanyList } from '@/api/company';
const router = useRouter()
const route = useRoute();
const form = reactive({
  projectName: '',
  phone: '',
  projectAmount: '',
  projectCode: '',
  intro: '',
  subsidizeAmount: '',
  approvalTime: '',
  subsidizeTime: ''
})

const onSubmit = () => {
  let { projectName, phone,projectAmount,projectCode,intro,subsidizeAmount,approvalTime,subsidizeTime} = form;
  const params = {
    projectName,
    phone,
    projectCode,
    projectAmount,
    companyId: companyId.value,
    investmentDirection: directionId.value,
    approvalTime,
    intro,
    subsidizeAmount,
    personId: talentId.value,
    completeMark: isjxId.value,
    proLevel: prolevelId.value,
    subsidizeProject: zzxmId.value,
    subsidizeTime,
    subsidizePhase: zzjdId.value,
    projectDuration: inputValue.value,
    approvalDepartment: departmentId.value
  }
  console.log('params:',params)
  creatProject(params).then((res) => {
    if (res.code === 200) {
      showToast(res.msg)
      router.push({ path: '/CompanyInfo', query: { status: '2' }})
    } else {
      showToast(res.msg)
    }
  }).catch((err) => {
    console.log(err)
  })
}

//所属单位
const page = ref({
currentPage: 1,
pageSize: 20,
});

const companyList = [];
const finished = ref(false);

//  下拉刷新
// const reFetchData = () => {
// page.value.currentPage = 1;
// finished.value = false;
// companyList = []
// debounce(fetchData, 800)();
// }

//  防抖
function debounce(func, delay) {
 let timeout
 return function () {
     const _this = this
     const args = [...arguments]
     if (timeout) {
         clearTimeout(timeout)
     }
     timeout = setTimeout(() => {
         func.apply(_this, args)
     }, delay)
 }
}


async function fetchData() {
if (finished.value) return;
const { code, data, msg } = await getCompanyList(page.value);
if (code == 200) {
  const { currentPage, pageSize, total } = data.pagination;
  // 判断是否到底
  if (currentPage * pageSize >= total) {
    finished.value = true;
  }
  // companyList.value = data.list;
  data.list.forEach(item=>{
    companyList.push({
        text: item.companyName,
        value: item.companyId
      })
    })

  //  准备加载新的数据
  page.value.currentPage++;
}else{
  showToast(msg)
}
}

const showPickerCompany = ref(false);
const companyId = ref('')
const companyValue = ref('')
const onConfirmCompany = ({ selectedOptions }) => {
showPickerCompany.value = false;
companyValue.value = selectedOptions[0]?.text;
companyId.value = selectedOptions[0]?.value;
console.log('companyValue.value:',companyValue.value);
console.log('companyId.value:',companyId.value);
};


const talentList = []
const getTalent = async () => {
  const { code, data } = await getTalentList({
    currentPage: 1,
    pageSize: 20
  });
  if (code === 200) {
    data.list.forEach(item=>{
        talentList.push({
          text: item.name,
          value: item.personId
        })
      })
  }
}
const showPicker1 = ref(false);
const talentId = ref('')
const talentValue = ref('')
const onConfirm1 = ({ selectedOptions }) => {
  showPicker1.value = false;
  talentValue.value = selectedOptions[0]?.text;
  talentId.value = selectedOptions[0]?.value;
};

const isjxList = [
  { text: '是', value: '1' },
  { text: '否', value: '0' },
];
const showPicker2 = ref(false);
const isjxId = ref('')
const isjxValue = ref('')
const onConfirm2 = ({ selectedOptions }) => {
  showPicker2.value = false;
  isjxValue.value = selectedOptions[0]?.text;
  isjxId.value = selectedOptions[0]?.value;
};

const prolevelList = [];
const getLevelList = () => {
  getDictSelect('talent_project_level').then(res => {
    const {code,data} = res
    if(code === 200){
        data.forEach(item=>{
        prolevelList.push({
          text: item.fullName,
          value: item.enCode
        })
      })
    }
  })
}
const showPicker3 = ref(false);
const prolevelId = ref('')
const prolevelValue = ref('')
const onConfirm3 = ({ selectedOptions }) => {
  showPicker3.value = false;
  prolevelValue.value = selectedOptions[0]?.text;
  prolevelId.value = selectedOptions[0]?.value;
};


//投资方向
const directionList = [];
const getDirectionList = () => {
  getDictSelect('talent_company_profession').then(res => {
    const {code,data} = res
    if(code === 200){
        data.forEach(item=>{
          directionList.push({
          text: item.fullName,
          value: item.enCode
        })
      })
    }
  })
}
const showPickerDirection = ref(false);
const directionId = ref('')
const directionValue = ref('')
const onConfirmDirection = ({ selectedOptions }) => {
  showPickerDirection.value = false;
  directionValue.value = selectedOptions[0]?.text;
  directionId.value = selectedOptions[0]?.value;
  console.log('directionId.value:',directionId.value);
};

//立项部门
const departmentList = [];
const getDepartmentList = () => {
  getDictSelect('talent_project_approval_department').then(res => {
    const {code,data} = res
    if(code === 200){
        data.forEach(item=>{
          departmentList.push({
          text: item.fullName,
          value: item.enCode
        })
      })
    }
  })
}
const showPickerDepartment = ref(false);
const departmentId = ref('')
const departmentValue = ref('')
const onConfirmDepartment = ({ selectedOptions }) => {
  showPickerDepartment.value = false;
  departmentValue.value = selectedOptions[0]?.text;
  departmentId.value = selectedOptions[0]?.value;
  console.log('departmentId.value:',departmentId.value);
};


const zzxmList = [];
const getZzxmList = () => {
  getDictSelect('talent_project_subsidize_project').then(res => {
    const {code,data} = res
    if(code === 200){
        data.forEach(item=>{
          zzxmList.push({
          text: item.fullName,
          value: item.enCode
        })
      })
    }
  })
}
const showPickerzzxm = ref(false);
const zzxmId = ref('')
const zzxmValue = ref('')
const onConfirmZzxm = ({ selectedOptions }) => {
  showPickerzzxm.value = false;
  zzxmValue.value = selectedOptions[0]?.text;
  zzxmId.value = selectedOptions[0]?.value;
};


const zzjdList = [];
const getZzjdList = () => {
  getDictSelect('talent_project_subsidize_phase').then(res => {
    const {code,data} = res
    if(code === 200){
        data.forEach(item=>{
          zzjdList.push({
          text: item.fullName,
          value: item.enCode
        })
      })
    }
  })
}
const showPickerzzjd = ref(false);
const zzjdId = ref('')
const zzjdValue = ref('')
const onConfirmZzjd = ({ selectedOptions }) => {
  showPickerzzjd.value = false;
  zzjdValue.value = selectedOptions[0]?.text;
  zzjdId.value = selectedOptions[0]?.value;
};

const showApprovalTime = ref(false);
const onConfirmTime = (selectedOptions) => {
  showApprovalTime.value = false;
  form.approvalTime = selectedOptions.selectedValues.map((option) => option).join('-');
  console.log('form.approvalTime:',form.approvalTime);
  if(inputValue.value){
    const futureDate = getFutureDate(inputValue.value).toISOString(); // 向后推几个月,日期的ISO字符串
    console.log('futureDate:',futureDate);
    const currentIso = new Date().toISOString()
    console.log('currentIso:',currentIso);
    if(futureDate > currentIso){
      console.log('已结项');
      isjxValue.value = '是'
      isjxId.value = '1'
      console.log('isjxValue.value:',isjxValue.value);
      console.log('isjxId.value:',isjxId.value);
    }else{
      console.log('未结项'); 
      isjxValue.value = '否'
      isjxId.value = '0'
      console.log('isjxValue.value:',isjxValue.value);
      console.log('isjxId.value:',isjxId.value);
    }
  }
};

const isDatePickerVisible = ref(false);
const PickerVisible = () =>{
  isDatePickerVisible.value = true;
}
const currentDate = ref(['2024', '01']);
const columnsType = ['year', 'month'];

const formatter = (type, option) => {
  if (type === 'year') {
    option.text += '年';
  }
  if (type === 'month') {
    option.text += '月';
  }
  return option;
};

const onConfirmTime2 = (selectedOptions) => {
  isDatePickerVisible.value = false;
  console.log('selectedOptions:',selectedOptions);
  form.subsidizeTime = selectedOptions.selectedValues.map((option) => option).join('-');
  console.log('form.subsidizeTime:',form.subsidizeTime);
};


const inputValue = ref('');
watch(inputValue, (newValue) => {
  if (newValue) {
    inputValue.value = parseFloat(newValue).toFixed(1);
    if(form.approvalTime){
      const futureDate = getFutureDate(inputValue.value).toISOString(); // 向后推几个月,日期的ISO字符串
      console.log('futureDate:',futureDate);
      const currentIso = new Date().toISOString()
      console.log('currentIso:',currentIso);
      if(futureDate > currentIso){
        console.log('已结项');
        isjxValue.value = '是'
        isjxId.value = '1'
        console.log('isjxValue.value:',isjxValue.value);
        console.log('isjxId.value:',isjxId.value);
      }else{
        console.log('未结项'); 
        isjxValue.value = '否'
        isjxId.value = '0'
        console.log('isjxValue.value:',isjxValue.value);
        console.log('isjxId.value:',isjxId.value);
      }
    }
  }
});

function getFutureDate(months) {
    const now = new Date(form.approvalTime); // 当前日期和时间
    now.setMonth(now.getMonth() + months); // 当前月份加上参数月份数
    return now; // 返回计算后的日期
}

onMounted(() => {
  fetchData()
  getTalent()
  getLevelList()
  getZzxmList()
  getZzjdList()
  getDirectionList()
  getDepartmentList()
})
</script>
 

<style lang="scss" scoped>
.container {
  background: #f9f9f9;
  overflow: hidden;
  margin-bottom: 45px;
  padding: 0.9rem 1.3rem 1.7rem;
}
.navbar {
    position: fixed;
    top: 0;
    width: 100%;
    background-color: #fff;
}
.addbtn{
  position: fixed;
  bottom: 2rem;
  width: 92%;
  left: 4%;
}
.van-button{
  font-size: 1.8rem;
  font-weight: 400;
}
.van-form{
  padding: 0 0 2rem 0;
}
.van-cell-group{
  background: #fff;
}
.van-field{
 border-bottom: 1px solid #E0E0E4;
 padding: 2rem 0 1.6rem;
}
.title{
    font-size: 1.8rem;
    font-weight: 700;
    margin: 0 0 1.5rem 1.2rem;
}
.qiye-info{
    background: #fff;
    padding: 1.2rem 0 1.5rem 0;
}
.qita{
    margin-top: 2rem;
    padding: 1.2rem;
    background: #fff;
    margin-bottom: 2.6rem;
}
.title2{
    font-size: 1.8rem;
    font-weight: 700;
    margin: 0 0 1.5rem 0;
}
.title3{
    font-size: 1.4rem;
    font-weight: 400;
    margin: 0 0 0.9rem 0;
}

::v-deep .van-field__label{
  width: 10rem!important;
}
.van-cell{
  border-bottom: 1px solid #E0E0E4;
  padding: 2rem 0 1.6rem;
}
::v-deep .van-cell__title{
  width: 10.6rem !important;
  flex: none;
  margin-right: 1.2rem;
}
::v-deep .van-cell__value{
  text-align: left;
  color: #323233;
}

</style>